package com.yipi.yupicturebackend.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yipi.yupicturebackend.constant.UserConstant;
import com.yipi.yupicturebackend.entity.User;
import com.yipi.yupicturebackend.exception.BusinessException;
import com.yipi.yupicturebackend.exception.ErrorCode;
import com.yipi.yupicturebackend.mapper.UserMapper;
import com.yipi.yupicturebackend.model.VO.LoginUserVO;
import com.yipi.yupicturebackend.model.enums.UserRoleEnum;
import com.yipi.yupicturebackend.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;

/**
* @author WJY
* @description 针对表【user(用户)】的数据库操作Service实现
* @createDate 2025-02-13 16:50:39
*/
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{
    @Override
    public long UserRegister(String userAccount, String passWord, String checkPassward) {
        //检验
        if (StrUtil.hasBlank(userAccount, passWord, checkPassward)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"参数为空");
        }
        if (userAccount.length() < 4){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"用户账号过短");
        }
        if (passWord.length() < 8){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"密码过短");
        }
        if (!passWord.equals(checkPassward)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"两次密码不一致");
        }
        //检查是否重复
        final QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        long count =  this.baseMapper.selectCount(queryWrapper);
        if (count > 0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户已存在");
        }
        //加密
        String encryptPassward = getEncryPassword(passWord);
        //插入数据
        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserName("无名");
        user.setUserPassword(encryptPassward);
        user.setUserRole(UserRoleEnum.USER.getValue());
        boolean saveResult = this.save(user);
        if (!saveResult){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"注册失败，数据库错误");
        }
        return user.getId();
    }

    @Override
    public LoginUserVO userLogin(String userAccount, String userPassword, HttpServletRequest request) {
        //校验
        if (StrUtil.hasBlank(userAccount, userPassword)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if (userAccount.length() < 4){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号过短");
        }
        if (userPassword.length() < 8){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码过短");
        }
        //加密
        String encryptPassward = getEncryPassword(userPassword);
        //查询用户是否存在
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("userAccount",userAccount);
        userQueryWrapper.eq("userPassword",encryptPassward);
        User user = this.baseMapper.selectOne(userQueryWrapper);
        //用户不存在
        if (user == null){
            log.info("user login failed, userAccount cannot match userPassward");
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户不存在或密码错误");
        }
        //用户存在，记录用户登录态
        request.getSession().setAttribute(UserConstant.USER_LOGIN_STATE, user);
        return this.getLoginUserVO(user);
    }

    /**
     * 用户注销
     * @param request
     * @return
     */
    @Override
    public boolean userLogout(HttpServletRequest request) {
        Object ojb = request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        if (ojb == null){
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"未登录");
        }
        request.getSession().removeAttribute(UserConstant.USER_LOGIN_STATE);
        return true;
    }

    @Override
    public User getLoginUser(HttpServletRequest request) {

        //判断是否已登录
        Object userObj = request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        User currentUser = (User) userObj;
        if (currentUser == null || currentUser.getId() ==null){
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        //向数据库根据当前用户id查询
        //Long userId = currentUser.getId();
        currentUser = this.getById(currentUser.getId());
        if (currentUser == null){
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        return currentUser;
    }

    /**
     * 获得脱敏后的用户信息
     * @param user
     * @return
     */
    public LoginUserVO getLoginUserVO(User user) {
        if (user == null){
            return null;
        }
        LoginUserVO loginUserVO = new LoginUserVO();
        BeanUtils.copyProperties(loginUserVO, user);
        return loginUserVO;
    }

    public String getEncryPassword(String passWord) {
        final String SALT = "yupi";
        return DigestUtils.md5DigestAsHex((SALT + passWord).getBytes());
    }


    /**
     * 用户注册接口
     */


}




